package chances.wechat.applet;

import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import chances.utils.JsonUtils;
import chances.wechat.entity.WechatUser;
import chances.wechat.service.BaseService;
import chances.wechat.service.WechatUserService;

@RestController
@RequestMapping(path = "/applet")
public class AppletLogin {

    @Value("${wechat.gateway.applet.appId}")
    private String appletAppId;

    @Value("${wechat.gateway.applet.secret}")
    private String appletSecret;

    @Value("${wechat.gate.url}")
    private String wechatGateUrl;

    @Autowired
    WechatUserService userService;

    @Autowired
    BaseService baseService;

    Logger appletlogger = LoggerFactory.getLogger("mprogramLogger");

    /**
     * 登录方法，入口
     * 
     * @param app_code
     *            必填 用于获取小程序的AppID
     * @param code
     *            必填 小程序登录时获得的用户登录凭证（有效期五分钟），用于获取ession_key
     * @return
     * @return 返回登录结果
     * @throws IOException
     */
    @PostMapping(path = "/openId")
    public LoginResult login(HttpServletRequest request,
            HttpServletResponse response, @RequestParam("code") String code,
            @RequestBody WechatUser user) throws IOException {
        LoginResult loginResult = new LoginResult();

        try {
            String requestUrl = wechatGateUrl + "/applet/getOpenId?appId="
                    + appletAppId + "&secret=" + appletSecret + "&code=" + code;
            appletlogger.info("url:{}", requestUrl);
            String resultJson = baseService.getMethod(requestUrl);
            appletlogger.info("result:{}", resultJson);

            Map<String, Object> resultMap = JsonUtils.toMap(resultJson);
            loginResult.setStatus((Integer) resultMap.get("status"));
            loginResult.setMessage((String) resultMap.get("message"));
            String openId = (String) resultMap.get("result");
            loginResult.setOpenId(openId);
            if (StringUtils.isNotBlank(openId)) {
                WechatUser wechaUser = userService.getWechatUser(openId);
                if (wechaUser == null) {
                    user.setOpenId(openId);
                    userService.insertWeixinUser(user);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            loginResult.setMessage(e.getMessage());
            loginResult.setStatus(500);
        }
        return loginResult;
    }

//    /**
//     * TODO 通过请求微信提供的API来获取SessionData
//     * 
//     * @param appId
//     *            小程序唯一标识
//     * @param secret
//     *            小程序的app secret
//     * @param code
//     *            小程序登录时获取的 code
//     * @return session_key，用于解密用户信息
//     */
//    public SessionData requestSessionData(String appId, String secret,
//            String code) {
//        String requestUrl = wechatGateUrl + "/getOpenId?appiId=" + appId
//                + "&secret=" + secret + "&code=" + code;
//        appletlogger.info("url:{}", requestUrl);
//
//        String resultJson = baseService.getMethod(requestUrl);
//        appletlogger.info("result:{}", resultJson);
//
//        SessionData sessionData = new SessionData();
//        Map<String, Object> contentMap = JSONUtils.toMap(resultJson);
//        if (contentMap.get("errcode") == null) {
//            sessionData.setSessionKey((String) contentMap.get("session_key"));
//            sessionData.setExpiresIn((int) contentMap.get("expires_in"));
//            sessionData.setOpenId((String) contentMap.get("openid"));
//        } else {
//            sessionData.setErrcode((int) contentMap.get("errcode"));
//            sessionData.setErrmsg((String) contentMap.get("errmsg"));
//        }
//        return sessionData;
//    }
}
